package com.easyExcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ExcelUtil {

    public static void write(String path, Class classType, List dataList){
        EasyExcel.write(path, classType).needHead(false).sheet().doWrite(dataList);
    }

    public static void write(String path, Class classType, String templateName, List dataList){
        EasyExcel.write(path, classType).withTemplate(templateName).sheet().doWrite(dataList);
    }

    public static void write(String path, Class classType, String templateName, Integer sheetNo, List dataList){
        EasyExcel.write(path, classType).withTemplate(templateName).sheet(sheetNo).doWrite(dataList);
    }

    public static void write(String path, Class classType, String templateName, String sheetName, List dataList){
        EasyExcel.write(path, classType).withTemplate(templateName).sheet(sheetName).doWrite(dataList);
    }

    public static void read(String path, Class classType){
        // return EasyExcel.read(path, classType, new UserListener()).sheet(0).doReadSync();
        // 同步读取单个工作簿
        String fileName = "D:\\excel\\write.xlsx";
        EasyExcel.read(fileName, User.class, new ReadListener<User>() {

            /***
             * 批量处理阈值
             */
            private static final int MAX_COUNT = 3000;

            /***
             * 批量处理集合
             */
            List<User> list = new ArrayList();

            @Override
            public void invoke(User user, AnalysisContext analysisContext) {
                list.add(user);
                // 达到阈值后进行处理，防止几万条数据在内存，产生OOM
                if (list.size() >= MAX_COUNT){
                    saveData(list);
                    list.clear();
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                saveData(list);
                list.clear();
                System.out.println("读取完成");
            }

            // 读取的数据处理
            public void saveData(List<User> list){
                for (User user : list) {
                    System.err.println(user);
                }
            }

        }).sheet().doRead();

    }

    public static List<Map<String, Object>> read(String path, Class classType, String sheetName){
        List<Map<String, Object>> dataList = EasyExcel.read(path, classType, new UserListener()).sheet(sheetName).doReadSync();
        return dataList;
    }

    public static List<Map<String, Object>> read(String path, Class classType, Integer sheetNo){
        return EasyExcel.read(path, classType, new UserListener()).sheet(sheetNo).doReadSync();
    }

    public static <T> List<T> readAll(String path, Class<T> classType){
        return EasyExcel.read(path).head(classType).doReadAllSync();
    }

}
